<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[1511]">
        <el-form-item :label="$t('所属租户')">
          <el-select
              style="width: 100%"
              v-model="page.adminUserId"
              @change="tenantChange"
              clearable
          >
            <el-option
                v-for="item in tenantList"
                :key="item.adminUserId"
                :label="item.adminName"
                :value="item.adminUserId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('APP名称')">
          <el-select
              style="width: 100%"
              v-model="page.productName"
              clearable
          >
            <el-option
                v-for="item in productList"
                :key="item.productId"
                :label="item.appName"
                :value="item.productName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')">
          <el-input v-model="page.userName"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号')">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证号码')" label-width="100px">
          <el-input v-model="page.idCard"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('优惠券名称')" label-width="100px">
          <el-input v-model="page.name"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('优惠券类型')" label-width="100px">
          <el-select style="width: 100%" v-model="page.type" clearable>
            <el-option v-for="item in couponType" :value="item.value" :key="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('操作人')">
          <el-select style="width: 100%" v-model="page.operatorId" clearable>
            <el-option v-for="item in operatorSelect" :value="item.operatorId" :key="item.operatorId"
                       :label="item.operatorName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="margin-bottom:10px;text-align: right">
        <el-button type="primary" v-show="$permiss[1506]" @click="giveCoupon">{{ $t('赠送优惠券') }}</el-button>
      </div>
      <Table :table-data="tableData" :table-column="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <template slot="type" slot-scope="{row}">
          {{ couponType.find(item => item.value === row.type).label }}
        </template>
      </Table>
    </el-card>

    <!--    赠送优惠券-->
    <Dialog :visible.sync="visibleDetails" :title="$t('赠送优惠券')" @cancel="visibleDetails = false" width="65%"
            @close="clearUserForm"
            @confirm="selectCouponConfirm">
      <el-row :gutter="24" style="margin: 15px 0 ">
        <el-form ref="userForm" :model="userPage" label-width="80px">
          <el-form-item :label="$t('赠送用户')" :rules="rulesUser" prop="productName">
            <el-col :span="6">
              <el-select
                  style="width: 100%"
                  v-model="userPage.productName"
                  :placeholder="$t('请选择APP')"
                  clearable
              >
                <el-option
                    v-for="item in productList"
                    :key="item.productId"
                    :label="item.appName"
                    :value="item.productName"
                ></el-option>
              </el-select>
            </el-col>
            <el-col style="line-height: 32px;text-align: center;width:24px">-</el-col>
            <el-col :span="6">
              <el-input :placeholder="$t('请输入手机号')" v-model="userPage.phone"/>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-button type="primary" @click="getUser">{{ $t('查询') }}</el-button>
              <el-button @click="clearUserSearch">{{ $t('重置') }}</el-button>
            </el-col>

          </el-form-item>

          <Table border :table-data="userTableData" :table-column="userTableColumn" :page="false"></Table>
          <h3>{{ $t('选择优惠券') }}</h3>
          <Table border :tableData="selectCouponTableData" :page="selectCouponPage"
                 @handleSizeChange="useHandleSizeChange"
                 @handleCurrentChange="useHandleCurrentChange">
            <el-table-column align="center">
              <template slot-scope="{row}">
                <el-radio :label="row.id" :value="selectCouponKey" @change="selectCouponChange($event,row.id)">{{
                    ' '
                  }}
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column :label="$t('优惠券名称')" prop="name" align="center"></el-table-column>
            <el-table-column :label="$t('优惠券类型')" prop="type" align="center">
              <template  slot-scope="{row}">
                {{ couponType.find(item => item.value === row.type).label }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('面额')" prop="amount" align="center"></el-table-column>
            <el-table-column :label="$t('有效天数')" prop="validDay" align="center"></el-table-column>
          </Table>
          <el-form-item :label="$t('备注')" style="margin-top:20px">
            <el-input type="textarea" :rows="4" v-model="userPage.remark"/>
          </el-form-item>
        </el-form>
      </el-row>
    </Dialog>
  </div>
</template>

<script>
import {manualSendList, fetchUserByPhone, fetchGiveList, giveCoupon, fetchHandlePersonal} from "@/api/marketing";
import {selectTenant, selectProduct} from "@/api/system";

export default {
  name: "CouponManualSendList",
  data() {
    return {
      tenantList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableColumn: [
        {label: this.$t("用户姓名"), prop: 'userName', minWidth: 100},
        {label: this.$t("手机号"), prop: 'phone', minWidth: 100,},
        {label: this.$t("身份证号码"), prop: 'idCard', minWidth: 100},
        {label: this.$t("APP名称"), prop: 'appName', minWidth: 100},
        {label: this.$t("优惠券名称"), prop: 'name', minWidth: 100},
        {label: this.$t("优惠券类型"), prop: 'type', minWidth: 100, slot: 'type'},
        {label: this.$t("面额"), prop: 'amount', minWidth: 100,},
        {label: this.$t("有效天数"), prop: 'validDay', minWidth: 100,},
        {label: this.$t("操作时间"), prop: 'getTime', minWidth: 150,},
        {label: this.$t("操作人"), prop: 'operatorName', minWidth: 150,},
        {label: this.$t("备注"), prop: 'remark', minWidth: 150,},
      ],
      tableData: [],
      couponType: [
        {label: this.$t("免息券"), value: 1},
        {label: this.$t("还款券"), value: 2},
        {label: this.$t("罚息券"), value: 3}
      ],
      userTableData: [],
      userTableColumn: [
        {label: this.$t("用户姓名"), prop: 'name', minWidth: 100},
        {label: this.$t("手机号"), prop: 'phone', minWidth: 100},
        {label: this.$t("身份证号码"), prop: 'idcard', minWidth: 100,},
        {label: this.$t("APP名称"), prop: 'appName', minWidth: 100},
      ],
      visibleDetails: false,
      tableRows: {},
      userPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        productName: null,
        phone: null,
        remark: ''
      },
      rulesUser: [
        {
          required: true, validator: (rules, value, callback) => {
            const {productName, phone} = this.userPage
            if (!productName || !phone) {
              return callback(new Error(this.$t('不能为空')))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      selectCouponPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      selectCouponKey: null,
      selectCouponAllKey: [],
      selectCouponTableData: [],
      productList: [],
      operatorSelect: []
    }
  },

  mounted() {
    this.getTableData()
    selectTenant().then(res => {
      this.tenantList = res.data
      if (this.tenantList.length > 0) this.$set(this.page, 'adminUserId', this.tenantList[0].adminUserId)
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
    fetchHandlePersonal().then(res => {
      this.operatorSelect = res.data
    })
  },
  methods: {
    async getTableData() {
      const params = {
        ...this.page,
      }
      const res = await manualSendList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list
        this.page.total = total
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    giveCoupon() {
      this.visibleDetails = true
    },
    // 查询用户
    async getUser() {
      this.$refs.userForm.validate(async v => {
        if (v) {
          const res = await fetchUserByPhone(this.userPage)
          this.getGiveCoupon()
          if (res.code === 1 && res.data) {
            this.userTableData = [res.data]
          } else {
            this.userTableData = []
          }
        }
      })
    },
    clearUserForm() {
      this.userPage.phone = null
      this.userTableData = []
      this.selectCouponTableData = []
      this.selectCouponKey = null
      this.$nextTick(() => {
        this.$refs.userForm.resetFields()
      })
    },
    //  获取可赠送优惠券列表
    async getGiveCoupon() {
      const res = await fetchGiveList({
        ...this.selectCouponPage,
        productName: this.userPage.productName
      })
      if (res.code === 1) {
        const {list, total} = res.data
        this.selectCouponTableData = list
        this.selectCouponPage.total = total
      }
    },
    // 赠送优惠券提交
    selectCouponConfirm() {
      this.$refs.userForm.validate(async v => {
        if (v) {
          if (!this.selectCouponKey) {
            return this.$message.error(this.$t('请选择优惠券!'))
          }
          const userInfo = [...this.userTableData][0]
          const res = await giveCoupon({
            couponId: this.selectCouponKey,
            ...userInfo,
            userName: userInfo.name,
            name: null,
            remark: this.userPage.remark,
          })
          if (res.code === 1) {
            this.$message.success(this.$t('赠送成功'))
            this.visibleDetails = false
            this.getTableData()
          }
        }
      })
    },
    clearUserSearch() {
      this.$refs.userForm.resetFields()
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', [])
      })
    },
    selectCouponChange(value, key) {
      this.selectCouponKey = key
    },
    useHandleSizeChange(val) {
      this.page.pageSize = val
      this.getCouponConsume()
    },
    useHandleCurrentChange(val) {
      this.page.pageNum = val
      this.getCouponConsume()
    },
  },

}
</script>

<style scoped>

</style>
